# 导包
from time import sleep
from selenium.common.exceptions import InvalidArgumentException, WebDriverException, TimeoutException
from selenium.webdriver.common.by import By
from selenium.webdriver import ActionChains
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC


class Base:
    """
    封装selenium基础方法
    """

    # 打开浏览器
    def __init__(self, driver):
        self.driver = driver

    # 请求目标网址
    def get(self, url):
        try:
            self.driver.get(url)
        except (InvalidArgumentException, WebDriverException):  # 捕获可能出现到的异常
            print('输入的网址不正确')

    # 定位元素
    def find_element(self, locator):
        try:
            return WebDriverWait(self.driver, timeout=5).until(EC.presence_of_element_located(locator), '元素定位失败')
        except TimeoutException:
            print('元素定位失败')

    # 元素input输入内容操作
    def send_keys(self, locator, text):
        element = self.find_element(locator)  # 调用对象方法find_element获取定位到的元素对象
        if element:
            element.send_keys(text)

    # 元素点击操作
    def click(self, locator):
        element = self.find_element(locator)  # 调用对象方法find_element获取定位到的元素对象
        if element:
            element.click()

    # 获取元素的源代码
    def get_attribute(self, locator, value):
        element = self.find_element(locator)  # 调用对象方法find_element获取定位到的元素对象
        if element:
            return element.get_attribute(value)

    # 获取元素的文本内容
    def get_text(self, locator):
        element = self.find_element(locator)  # 调用对象方法find_element获取定位到的元素对象
        if element:
            return element.text

    # 浏览器前进操作
    def browser_forward(self):
        self.driver.forward()

    # 浏览器后退操作
    def browser_back(self):
        self.driver.back()

    # 浏览器刷新操作
    def browser_refresh(self):
        self.driver.refresh()

    # 关闭浏览器
    def quit(self, seconds=0):
        sleep(seconds)
        self.driver.quit()


if __name__ == '__main__':
    base = Base('chrome')
    base.get('https://www.baidu.com/')
    # base.find_element((By.ID, 'kw'))
    # base.get_attribute((By.ID, 'kw'))
    sleep(2)
    base.send_keys((By.ID, 'kw'), 'python')
    base.click((By.ID, 'su'))
    sleep(2)
    base.browser_back()
    sleep(2)
    base.browser_forward()
    sleep(2)
    base.browser_refresh()
    base.quit(2)
